package com.chenbei.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.system.domain.SysDict;
import com.chenbei.system.mapper.SysDictMapper;
import com.chenbei.system.service.ISysDictService;
import com.chenbei.system.vo.req.SysDictReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SysDictService extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
    @Override
    public void add(SysDict sysDict) {
        LambdaQueryWrapper<SysDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDict::getKeyName, sysDict.getKeyName()).or().eq(SysDict::getName, sysDict.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("字典名称或键名已存在");
        }
        if (sysDict.getStatus() == null) {
            sysDict.setStatus(1);
        }
        save(sysDict);
    }

    @Override
    public void deleteById(long id) {
        removeById(id);
    }

    @Override
    public void update(SysDict sysDict) {
        LambdaQueryWrapper<SysDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(SysDict::getId, sysDict.getId()).and(consumer -> {
            consumer.eq(SysDict::getKeyName, sysDict.getKeyName()).or().eq(SysDict::getName, sysDict.getName());
        });
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("字典名称或键名已存在");
        }
        updateById(sysDict);
    }

    @Override
    public Page<SysDict> listPage(SysDictReq sysDictReq) {
        LambdaQueryWrapper<SysDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(SysDict::getId);
        if (StringUtils.isNoneBlank(sysDictReq.getName())) {
            lambdaQueryWrapper.like(SysDict::getName, sysDictReq.getName());
        }
        if (StringUtils.isNoneBlank(sysDictReq.getKey())) {
            lambdaQueryWrapper.like(SysDict::getKeyName, sysDictReq.getKey());
        }
        if (sysDictReq.getStatus() != null && sysDictReq.getStatus() > 0) {
            lambdaQueryWrapper.eq(SysDict::getStatus, sysDictReq.getStatus());
        }
        Page<SysDict> pageConfig = new Page<>(sysDictReq.getPageNum(), sysDictReq.getPageSize());
        return page(pageConfig, lambdaQueryWrapper);
    }
}
